import canvas from './canvas'
const app = getApp()
const commissionApi = require('../../utils/commissionApi.js');
Page({
  data: {
    userInfo: {},
    showQrModal: false,
    summary: {},
    qrBase64: '',       // 从接口拿到的二维码base64字符串
    posterTempPath: '',  // 合成海报的临时文件路径
    loadingStatus: false,
  },
  onLoad() {
    const user = wx.getStorageSync('userInfo')
    this.setData({
      userInfo: user
    })
    this.initDetails()
  },
  onPullDownRefresh() {
    this.getData(() => {
      // 停止下拉刷新动画
      this.initDetails()
    })
  },
  initDetails() {
    commissionApi.getCommissionDetails({ user_id: this.data.userInfo.user_id })
      .then(res => {
        const { last_month, this_month, today, yesterday } = res.data
        this.setData({
          summary: res.data
        })
      })
  },
  onStudents() {
    wx.navigateTo({ url: '/pages/students/index' })
  },
  onDetail() {
    wx.navigateTo({ url: '/pages/commission/earnings/index' })
  },
  onWithdraw() {
    // wx.showToast({
    //   title: '余额提现未开放',
    //   icon: 'none'
    // })
    // return
    wx.navigateTo({ url: '/pages/commission/withdraw/index' })
  },

  onWithdrawRecord() {
    wx.navigateTo({ url: '/pages/commission/withdrawRecord/index' })
  },

  /**
   * 提现设置 跳转入口
   */
  onWithdrawalSettings() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  /**
   * 生成海报
  */
  onInvite() {
    wx.showLoading({
      title: '生成中...',
      mask: true // 可选，防止用户点击其他区域
    });
    commissionApi.get_qrcode().then(res => {
      if (res && res.image) {
        this.setData({
          qrBase64: res.image,
          showQrModal: true
        });
      } else {
        wx.showToast({
          title: '生成失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.showToast({
        title: '生成异常',
        icon: 'none'
      });
      console.error('生成海报失败', err);
    }).finally(() => {
      wx.hideLoading();
    });
  },

  closeQrModal() {
    this.setData({ showQrModal: false });
  },
  onImgOK(e) {
    console.log('生成成功', e.detail.path);
    wx.previewImage({ urls: [e.detail.path] });
  },
  base64ToPath(base64) {
    return new Promise((resolve, reject) => {
      const fs = wx.getFileSystemManager();
      const filePath = `${wx.env.USER_DATA_PATH}/qr_code.png`;
      const data = base64.replace(/^data:image\/\w+;base64,/, '');

      fs.writeFile({
        filePath: filePath,
        data: data,
        encoding: 'base64',
        success: () => resolve(filePath),
        fail: (err) => reject(err)
      });
    });
  },


  onSaveImage() {
    const base64 = this.data.qrBase64.replace(/^data:image\/\w+;base64,/, ""); // 去掉头部
    const filePath = `${wx.env.USER_DATA_PATH}/qr_code.png`; // 小程序临时路径
  
    const fs = wx.getFileSystemManager();
    fs.writeFile({
      filePath: filePath,
      data: base64,
      encoding: 'base64',
      success: () => {
        wx.saveImageToPhotosAlbum({
          filePath: filePath,
          success: () => {
            wx.showToast({ title: '已保存到相册', icon: 'success' });
          },
          fail: (err) => {
            wx.showToast({ title: '保存失败，长按图片保存！', icon: 'none' });
            console.error('保存失败', err);
          }
        });
      },
      fail: (err) => {
        wx.showToast({ title: '写入失败', icon: 'none' });
        console.error('写文件失败', err);
      }
    });
  },
  

  // 分享朋友圈提示
  onGuideMoment() {
    wx.showModal({
      title: '提示',
      content: '小程序暂不支持直接分享到朋友圈，请先保存图片再手动分享。',
      showCancel: false
    });
  },

  // 分享回调（选填）
  onShareAppMessage() {

    const userId = wx.getStorageInfoSync('userId')

    return {
      title: '我正在学法减分赚佣金，你也来看看！',
      path: '/pages/index/index?sharerId='+userId, // 替换成你的路径
      imageUrl: '/image/0404.png', // 分享封面图
    };
  }

})


